const Upyun = require('../SDK/upyun-wxapp-sdk')
const utils = require('../utils/util.js')
const app = getApp();



// 文件上传
export const upYunImg = function (imgListObj, token) {
  var getSignatureUrl = app.globalData.baseUrl + '/signature/upyun/wximg'
  const upyun = new Upyun({
    bucket: 'all-season', //云存储服务名
    operator: 'allseason', //操作员名
    getSignatureUrl: getSignatureUrl, //签名接口地址
    token: token
  })
  // const imgUrl = 'http://image.glowworm.club/'

  for (let index = 0; index < imgListObj.length; index++) {
    // var imgUrlList = [];
    let imageSrc = imgListObj[index].src;
    let imgName = imgListObj[index].imgName;

    upyun.upload({
      localPath: imageSrc,
      remotePath: 'CampusTinyVoice/'+imgName, //上传文件保存路径
      success: function (res) {
        // console.log('uploadImage success, res is:', res)
        // imgUrlList.push(imgUrl + imgName)

      },
      fail: function ({
        errMsg
      }) {
        utils.wxShowToastUtil("图片上传失败")
        console.log('图片上传失败', errMsg)
      }
    })

  }
}

export const upYunImgGetImgUrl = function (imgList, token) {
  // 要上传的图片地址,和名称
  let imgListObj = [];
  // 返回的上传后的图片url 列表
  let imgUpUrlList = [];
  const imgUrl = 'https://image.glowworm.club/'
  // const imgUrl = 'http://upimg.firebug.xyz/'

  for (let index = 0; index < imgList.length; index++) {
    // 构造图片对象,将图片地址和生成的uuid图片名封装
    let imgObj = {}
    imgObj['src'] = imgList[index]
    // 构造图片唯一名字 有后缀名
    let imgName = this.uuid() + imgList[index].substring(imgList[index].lastIndexOf('.'))
    imgObj['imgName'] = imgName

    // 将图片url添加进要返回的列表
    imgUpUrlList.push(imgUrl + imgName)
    // 将图片对象添加进列表
    imgListObj.push(imgObj)
  }

  this.upYunImg(imgListObj, token)

  return imgUpUrlList;



}


export function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid;

}